﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Diplo.Twitter;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using motion10.SharePoint.TwitterSupport.Common;
using System.Text;
using Microsoft.SharePoint.Portal.WebControls;
using System.Web;

namespace motion10.SharePoint.TwitterSupport.CONTROLTEMPLATES
{
    public partial class TwitterSupportControl : UserControl, ICallbackEventHandler
    {
        protected OAuthSecureStoreData _secureStoreData;
        protected string _callbackReturnValue;


        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(Request.QueryString["accountname"]) ||
                    HttpUtility.UrlDecode(Request.QueryString["accountname"]).ToLower() == SPContext.Current.Web.CurrentUser.LoginName.ToLower())
                {
                    if (!Page.IsPostBack)
                    {
                        this.Page.ClientScript.RegisterClientScriptInclude("TwitterStatusNotes", "/_layouts/motion10.SharePoint.TwitterSupport/twittersupport.js");

                        StringBuilder builder = new StringBuilder();

                        builder.Append(string.Format("LoadTwitterSupport( \"{0}\",  \"{1} \", \"{2}\");\r\n",
                                                        _secureStoreData.IsAuthenticated.ToString().ToLower(),
                                                        this.GetConnectToTwitterUrl(),
                                                        this.Page.ClientScript.GetCallbackEventReference(this, "arg", "TwitterRefreshNotes", "context", true)));

                        // Register the JavaScript
                        this.Page.ClientScript.RegisterStartupScript(base.GetType(), "TwitterStatusNotes", builder.ToString(), true);
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("An error occurred in the Twitter Support for SharePoint: " + ex.Message);
            }
        }

        /// <summary>
        /// Determine in which state the twitter sign on is.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this._secureStoreData = new OAuthSecureStoreData(SPContext.Current.Web.CurrentUser.LoginName);
            
            if (!this._secureStoreData.IsAuthenticated)
            {
                // Authentication in Progress...
                if (Page.Request.QueryString["oauth_token"] != null &&
                    Page.Request.QueryString["oauth_verifier"] != null)
                {
                    TwitterOAuth oauth = new TwitterOAuth(TwitterConsumerKeys.Local.ConsumerKeyName,
                                                            TwitterConsumerKeys.Local.ConsumerSecretName);

                    var response = oauth.GetAccessResponse(Page.Request);

                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        SPContext.Current.Web.AllowUnsafeUpdates = true;
                        // If the response is OK save the data using the IOAuthData save implementation
                        oauth.SaveValidatedDataFromResponse(response, SPContext.Current.Web.CurrentUser.LoginName);
                        SPContext.Current.Web.AllowUnsafeUpdates = false;
                        
                        Page.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true); 
                    }
                }
            }
        }

        /// <summary>
        /// Send back the result
        /// </summary>
        /// <returns></returns>
        string ICallbackEventHandler.GetCallbackResult()
        {
            return this._callbackReturnValue;
        }

        /// <summary>
        /// Pick up the event and send the message to Twitter
        /// </summary>
        /// <param name="eventArgument"></param>
        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            // If Twitter authorized then send the Tweet
            if (this._secureStoreData != null &&
                this._secureStoreData.IsAuthenticated)
            {
                SendTweet(eventArgument);
            }
        }

        /// <summary>
        /// Tweet the message and returns the statuscode.
        /// </summary>
        protected void SendTweet(string message)
        {
            TwitterPush twitter = new TwitterPush(this._secureStoreData,
                                                    TwitterConsumerKeys.Local.ConsumerKeyName,
                                                    TwitterConsumerKeys.Local.ConsumerSecretName);
            if (message.IndexOf("#tw") > -1)
            {
                TwitterResponse response = twitter.UpdateStatus(message);
                this._callbackReturnValue = response.Response.StatusDescription;
            }
        }


        /// <summary>
        /// Connect Twitter to SharePoint URL
        /// </summary>
        private string GetConnectToTwitterUrl()
        {
            string consumerkey = TwitterConsumerKeys.Local.ConsumerKeyName;
            string consumersecret = TwitterConsumerKeys.Local.ConsumerSecretName;

            // Create a new OAuth client using the key and secret stored in the data
            TwitterOAuth oauth = new TwitterOAuth(consumerkey, consumersecret);

            // Dynamically generate the callback URL for this site
            oauth.CallBackUrl = Page.Request.Url.AbsoluteUri;

            // Gets the token
            var token = oauth.GetAuthenticationToken();

            // Appends the token to the authorisation URL
            Uri authUri = oauth.GetAuthorisationUrl(token);

            // returns the URL to connect with Twitter
            return authUri.AbsoluteUri;
        }
    }
}
